import { addResizeListener, removeResizeListener } from 'element-plus/lib/utils/dom/resize-event'

/**
 * 自适应高度指令，使用方法：
 * <el-table height="100px" v-el-adaptive="{bottomOffset: 30}">...</el-table>
 * el-table height 属性必须设置
 * bottomOffset: 30(default)   // 默认底部距离
 */

const doResize = (el, binding, vnode) => {
  // const { componentInstance: $table } = vnode

  console.log(vnode)

  console.log(el)


  const { value } = binding

  // if (!$table.height) {
  //   throw new Error(`el-$table must set the height. Such as height='100px'`)
  // }
  const bottomOffset = (value && value.bottomOffset) || 30

  const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
  if (el.style.height != height + 'px') {
    el.style.height = height + 'px'
  }
  // $table.layout.setHeight(height)
  // $table.doLayout()
}

// let tableWrapper = null
// let lastScrollTop = 0

export const ElAdaptive = {
  beforeMount(el, binding, vnode) {

    console.log('beforeMount')

    el.resizeListener = () => {
      doResize(el, binding, vnode)
    }
    // parameter 1 is must be "Element" type
    addResizeListener(window.document.body, el.resizeListener)
  },
  mounted(el) {

    console.log('mounted')

    let tableWrapper = el.getElementsByClassName('el-scrollbar__wrap') && el.getElementsByClassName('el-scrollbar__wrap')[0]
    tableWrapper.addEventListener('scroll', function() {
      el.lastScrollTop = tableWrapper.scrollTop
    })
  },
  updated(el, binding, vnode, prevNode) {
  console.log(this)
    console.log('updated')

    doResize(el, binding, vnode, prevNode)

    let tableWrapper = el.getElementsByClassName('el-scrollbar__wrap') && el.getElementsByClassName('el-scrollbar__wrap')[0]
    if (tableWrapper && tableWrapper.scrollTop != el.lastScrollTop) {
      tableWrapper.scrollTop = el.lastScrollTop
    }
  },
  unbind(el) {

    console.log('unbind')

    removeResizeListener(window.document.body, el.resizeListener)
  }
}
